package de.imdb250junkie.locale;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author André Stannek
 * @version 2010-02-10
 */
public final class LocaleUtils
{
    /**
     * Set holding all available locales.
     */
    private static final transient Set<Locale> LOCALES = new HashSet<>();
    static
    {
        // add new locales here
        LOCALES.add(new Locale("de"));
        LOCALES.add(new Locale("de", "DE"));
        LOCALES.add(new Locale("en"));
        LOCALES.add(new Locale("en", "UK"));
    }

    /**
     * the currently used locale
     */
    private static transient Locale currentLocale;
    static
    {
        loadLocale();
    }

    /**
     * Masking Utility class constructor
     */
    private LocaleUtils()
    {
        /**/
    }

    /**
     * loads the last used locale from a file if possible.
     */
    private static void loadLocale()
    {
        try (ObjectInputStream objectIS = new ObjectInputStream(
                new FileInputStream("prefs.bin")))
        {
            final Object input = objectIS.readObject();
            currentLocale = (Locale) input;
        }
        catch (final IOException | ClassNotFoundException e)
        {
            currentLocale = Locale.getDefault();
        }
    }

    /**
     * saves the currently used locale to file.
     */
    private static void saveLocale()
    {
        try (ObjectOutputStream objectOS = new ObjectOutputStream(
                new FileOutputStream("prefs.bin")))
        {
            objectOS.writeObject(currentLocale);
        }
        catch (final IOException e)
        {
            Logger.getLogger("ERROR").log(Level.SEVERE,
                    "Locale could not be saved", e);
        }
    }

    /**
     * @return The Locales for which a translation file is available
     */
    public static Set<Locale> getAvailableLocales()
    {
        return LOCALES;
    }

    public static void setLocale(final Locale locale)
    {
        currentLocale = locale;
        saveLocale();
    }

    public static Locale getLocale()
    {
        return currentLocale;
    }
}
